package com.atguigu.daijia.common.config.redisson;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @create: 2024/9/26
 * @author: gyhe10
 * @description: Redisson 配置类
 **/

@Configuration
// @EnableConfigurationProperties({RedisProperties.class})
public class RedissonConfig {

    private static final String ADDRESS_PREFIX = "redis://";

    @Bean
    RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        if (!StringUtils.hasText(redisProperties.getHost())) {
            throw new GuiguException(ResultCodeEnum.REDIS_HOST_NOT_SET);
        }
        SingleServerConfig singleServerConfig = config.useSingleServer()
                .setAddress(ADDRESS_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setTimeout((int) redisProperties.getTimeout().toMillis());
        if (StringUtils.hasText(redisProperties.getPassword())) {
            singleServerConfig.setPassword(redisProperties.getPassword());
        }
        return Redisson.create(config);
    }
}
